package cuit.epoch.pymjl.security.controller;

//import cuit.epoch.pymjl.security.entity.ChatMessage;
//import org.springframework.messaging.handler.annotation.MessageMapping;
//import org.springframework.messaging.handler.annotation.Payload;
//import org.springframework.messaging.handler.annotation.SendTo;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.PathVariable;
//
//@Controller
//public class ChatController {
//
//    @MessageMapping("/chat")
//    @SendTo("/topic/messages")
//    public ChatMessage sendMessage(@PathVariable String roomId, @Payload ChatMessage message) {
//        return message;
//    }
//}

import com.alibaba.fastjson.JSON;
import cuit.epoch.pymjl.security.entity.ChatMessage;

import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/chat/{username}")
public class ChatController {
    //聊天室，存储所有用户的session
    public static final Map<String, Session> sessions = new HashMap<>();
    private Session session;
    //用户昵称
    private String username;
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "username") String username, @PathParam(value = "usernickname") String usernickname) {
        this.session = session;
        this.username = username;
        //加入聊天室
        sessions.put(username, session);
    }


    @OnClose
    public void onClose() {
        //退出聊天室
        sessions.remove(username);
    }

    @OnMessage
    public void onMessage(String msg) {
        //封装数据
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSender(username);
        chatMessage.setContent(msg);
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        chatMessage.setDate(formatter.format(date));
        chatMessage.setPepo(session.getMessageHandlers().size());
        //将java对象转为json字符串
        String jsonStr = JSON.toJSONString(chatMessage);
        //给所有聊天室用户推送消息
        for (Session session : sessions.values()) {
            try {
                session.getBasicRemote().sendText(jsonStr);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
